package com.qgs.secsgem.mq.consumer;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.qgs.secsgem.common.utils.CommonFunction;
import com.qgs.secsgem.mq.configuration.ConfigOfPID10_1;
import com.qgs.secsgem.mq.consumer.commonHandler.MQMessageHandler;
import com.qgs.secsgem.mq.entity.MQMessage;
import com.qgs.secsgem.mq.entity.common.Header;
import com.qgs.secsgem.mq.entity.common.Returns;
import com.qgs.secsgem.mq.entity.specificBody.QueryEQStatusBody;
import com.qgs.secsgem.mq.producer.component.RabbitSender;

import com.qgs.secsgem.secs.eq.runnable.PID10Runnable;


import com.qgs.secsgem.secs.hsmsss.HsmsSsCommunicator;
import com.rabbitmq.client.Channel;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.amqp.support.AmqpHeaders;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.Message;
import org.springframework.stereotype.Component;

import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;

/**
 * @Desc: "PID10_1设备 接收MQ消息 监听类"
 * @Author: caixiang
 * @DATE: 2021/6/22 15:30
 *
 * Ctrl+R 替换设备名
 */
@Component
public class PID10_1Received{

    private static final Logger logger = LoggerFactory.getLogger(PID10_1Received.class);

    @Autowired
    RabbitSender rabbitSender;

    @Autowired
    MQMessageHandler mqMessageHandler;

    private String exchangeName = ConfigOfPID10_1.EXCHANGE_NAME_PID10_1;
    private String routingKey = ConfigOfPID10_1.MES_RESPONSE_QUEUE_ROUTINGKEY_PID10_1;


    HsmsSsCommunicator comm = PID10Runnable.comm;

    /**
     * desc:  这个函数不太会用到，除非某些特殊场景
     *
     * */
    @RabbitListener(queues = ConfigOfPID10_1.EAP_RESPONSE_QUEUE_PID10_1)
    @RabbitHandler
    public void eapResponse(Message<?> message, Channel channel)throws Exception{

        logger.info("==============received message-EAP_REQUEST_QUEUE_PID10_1=================");

        Long deliveryTag = (Long)message.getHeaders().get(AmqpHeaders.DELIVERY_TAG);

        try {

            MQMessage mqMessage = CommonFunction.parse(message);
            String transactionId = mqMessage.getHeader().getTransactionId();
            System.out.println("收到的消息是: "+mqMessage.toString());
            //todo
//            channel.basicAck(deliveryTag,false);
        }catch (Exception e){
            // 第一个false 是 不批量签收；第二个false 是 不重回队列
            logger.error(e.getMessage());
            channel.basicNack(deliveryTag,false,false);
            return;
        }
    }




    private void parseAndReply(Header header, String body, Returns returns) throws Exception {
        MQMessage mqMessage = new MQMessage();
        header.setMessageType("Response");
        header.setSendTimestamp(CommonFunction.getNowDate(1));
        header.setFrom("EAP");
        header.setTo("MES");
        mqMessage.setHeader(header);
        mqMessage.setBody(body);
        mqMessage.setReturns(returns);
        rabbitSender.sendDirect(mqMessage,exchangeName,routingKey);
    }

//    @RabbitListener(queues = ConfigOfPID10_1.MES_REQUEST_QUEUE_PID10_1)
//    @RabbitHandler
//    public void mesRequest(Message<?> message, Channel channel)throws Exception{
//
//        logger.info("==============received message-EAP_REQUEST_QUEUE_PID10_1=================");
//
//        Long deliveryTag = (Long)message.getHeaders().get(AmqpHeaders.DELIVERY_TAG);
//        //MQMessage 中的 transactionId
////        String transactionId = (String)message.getHeaders().get("spring_returned_message_correlation");
////        //logger.info("transactionId:"+transactionId);
//
//        try {
//            MQMessage mqMessage = CommonFunction.parse(message);
//            String transactionId = mqMessage.getHeader().getTransactionId();
//            System.out.println("收到的消息是: "+mqMessage.toString());
//            System.out.println();
//            logger.info(mqMessage.toString());
//
//
//            switch(mqMessage.getHeader().getMessageName()) {
//
//                case EventNameConstant.S1F1:
//
//                    SECSCommand.areYouThere(comm);
//                    break;
//
//                case EventNameConstant.S1F3:
//                    S1F13EstablishCommunicationsBody body = JSONObject.parseObject(mqMessage.getBody(), S1F13EstablishCommunicationsBody.class);
//                    List<ResVIDNode> resVIDNodes = SECSCommand.queryEQPStatus(body.getVidList(), body.getVidType(), PID10Runnable.comm);
//                    parseAndReply(mqMessage.getHeader(), JSONObject.toJSONString(resVIDNodes), new Returns(Constant.ReturnsOK, ""));
//                    break;
//
//                default:
//
//                    break;
//
//            }
//
//
//
//
//            channel.basicAck(deliveryTag,false);
//            System.out.println(mqMessage.toString());
//        }catch (Exception e){
//            // 第一个false 是 不批量签收；第二个false 是 不重回队列
//            logger.error(e.getMessage());
//            channel.basicNack(deliveryTag,false,false);
//            return;
//        }
//
//    }
//


    public static void main(String[] args) {
        //localhost:8001


        MQMessage mqMessage = new MQMessage();

        Header header = new Header("Request","Execute","QUERYEQPStatus","12");
        QueryEQStatusBody queryEQStatusBody = new QueryEQStatusBody();
        queryEQStatusBody.setVidType("u4");
        List<String> vids = new ArrayList<>();
        vids.add("10000");
        vids.add("10001");
        vids.add("10002");
        queryEQStatusBody.setVidList(vids);

        //queryEQStatusBodys => {"vidList":["10000","10001","10002"],"vidType":"u4"}
        //bytes              => [123, 34, 118, 105, 100, 76, 105, 115, 116, 34, 58, 91, 34, 49, 48, 48, 48, 48, 34, 44, 34, 49, 48, 48, 48, 49, 34, 44, 34, 49, 48, 48, 48, 50, 34, 93, 44, 34, 118, 105, 100, 84, 121, 112, 101, 34, 58, 34, 117, 52, 34, 125]
        //"body":               "eyJ2aWRMaXN0IjpbIjEwMDAwIiwiMTAwMDEiLCIxMDAwMiJdLCJ2aWRUeXBlIjoidTQifQ=="
        //message => {"header":{"transactionId":"12_20210908141555_d7d88","messageType":"Request","messageCategory":"Execute","messageName":"QUERYEQPStatus","equipmentId":"12","sendTimestamp":"2021-09-08 14:15:56","from":"mes","to":"eap"},"body":"eyJ2aWRMaXN0IjpbIjEwMDAwIiwiMTAwMDEiLCIxMDAwMiJdLCJ2aWRUeXBlIjoidTQifQ=="}
        //new String(bytes) : {"vidType":"u4","vidList":["10000","10001","10002"]}
        String queryEQStatusBodys = JSONObject.toJSONString(queryEQStatusBody);


        byte[] bytes = JSONObject.toJSONBytes(queryEQStatusBody);
        System.out.println("myString :"+ new String(bytes));
        mqMessage.setBody(queryEQStatusBodys);
        mqMessage.setHeader(header);

        //{"header":{"transactionId":"12_20210908094750_d62d4","messageType":"Request","messageCategory":"Execute","messageName":"QUERYEQPStatus","equipmentId":"12","sendTimestamp":"2021-09-08 09:47:50","from":"mes","to":"eap"},"body":"eyJ2aWRMaXN0IjpbIjEwMDAwIiwiMTAwMDEiLCIxMDAwMiJdLCJ2aWRUeXBlIjoidTQifQ=="}
        String s = JSONObject.toJSONString(mqMessage);
        MQMessage mqMessagessss = JSONObject.parseObject(s.getBytes(StandardCharsets.UTF_8), MQMessage.class);
        System.out.println("mqMessagessss : " + mqMessagessss.toString());
        System.out.println(s);
        //String result= HttpUtil.post("localhost:8001/receivedFromEapRequest",s);

        //{"header":{"transactionId":"PIDPID10_1_20210908093729_95196","messageType":"Request","messageCategory":"Alarm","messageName":"AlarmTimeOut","from":"EAP","to":"MES","equipmentId":"PIDPID10_1","sendTimestamp":"2021-09-08 09:37:29"},"body":"eyJ2aWRMaXN0IjpbIjEwMDAwIiwiMTAwMDEiLCIxMDAwMiJdLCJ2aWRUeXBlIjoidTQifQ=="}
        String s22 = "{\"header\":{\"transactionId\":\"PIDPID10_1_20210908093729_95196\",\"messageType\":\"Request\",\"messageCategory\":\"Alarm\",\"messageName\":\"AlarmTimeOut\",\"from\":\"EAP\",\"to\":\"MES\",\"equipmentId\":\"PIDPID10_1\",\"sendTimestamp\":\"2021-09-08 09:37:29\"},\"body\":\"eyJ2aWRMaXN0IjpbIjEwMDAwIiwiMTAwMDEiLCIxMDAwMiJdLCJ2aWRUeXBlIjoidTQifQ==\"}";

        String s2 = "{\"header\":{\"transactionId\":\"PIDPID10_1_20210908093729_95196\",\"messageType\":\"Request\",\"messageCategory\":\"Alarm\",\"messageName\":\"AlarmTimeOut\",\"from\":\"EAP\",\"to\":\"MES\",\"equipmentId\":\"PIDPID10_1\",\"sendTimestamp\":\"2021-09-08 09:37:29\"},\"body\":{\"TransactionId:\":\"PIDPID10_1_20210908093644_71835\",\"MessageName:\":\"TraceData\"}}";
        JSONObject jsonObject = JSON.parseObject(s2);
        String header1 = jsonObject.getString("header");
        String body = jsonObject.getString("body");
        String returns = jsonObject.getString("returns");
        System.out.println("header: "+header1);
        System.out.println("body: "+body);
        System.out.println("returns: "+returns);

        byte[] bytes2 = s2.getBytes();
        MQMessage mqMessage2 = JSONObject.parseObject(bytes2, MQMessage.class);
        System.out.println(mqMessage2.toString());
    }

//    @RabbitListener(queues = ConfigOfPID10_1.MES_RESPONSE_QUEUE_PID10_1)
//    @RabbitHandler
//    public void mesResponse(Message<?> message, Channel channel)throws Exception{
//        logger.info("==============PIDPID10_1_Exchange-MES_Response_Queue=================,priority:"+message.getHeaders().get("priority")+",attr1"+message.getHeaders().get("attr1"));
//        Long deliveryTag = (Long)message.getHeaders().get(AmqpHeaders.DELIVERY_TAG);
//
//        //模拟异常 ，然后 拒签消息 ，然后丢到死信队列
//        try {
//            MQMessage mqMessage = CommonFunction.parse(message);
//            String transactionId = mqMessage.getHeader().getTransactionId();
//            Integer result = mqMessageHandler.responseHandler(message);
//            if(result == 1){
//                logger.info("在 MES_RESPONSE_QUEUE_PID10_1 队列中 , transitionId"+transactionId+" 这条消息处理成功");
//                channel.basicAck(deliveryTag,false);
//            }else {
//                logger.error("在 MES_RESPONSE_QUEUE_PID10_1 队列中 ,transitionId"+transactionId+" 处理消息的时候 出现异常，然后 拒签消息 ，然后丢到死信队列");
//                channel.basicNack(deliveryTag,false,false);
//            }
//
//            //throw new Exception("11111");
//        }catch (Exception e){
//            // 第一个false 是 不批量签收；第二个false 是 不重回队列
//            channel.basicNack(deliveryTag,false,false);
//            return;
//        }
//
//        //注意 这里特别注意 已经拒收的消息 再签收是要出错的，这里要特别注意。
//        //channel.basicAck(deliveryTag,false);
//
//    }

}
